#!/usr/bin/env perl
$print_on=0;
$need_right_curly=0;
open(F,">classPtr.i");
print << "END";
#ifdef SWIGPYTHON
%{
PyObject *py_mod;
%}
%init %{
   py_mod=PyImport_ImportModule("DEF");
%}
#else
#define L_OUTPUT OUTPUT
#endif
#ifdef SWIGTCL
%{
Tcl_Obj *
SWIG_Ptr2Obj(Tcl_Interp *interp,const char *classstr,
             struct swig_type_info *swig_type,void *source);

%}
#endif
END

$lang="perl5";
if($ARGV[0] =~ /^-perl/o){
   $lang="perl5";
   shift @ARGV;
}elsif($ARGV[0] =~ /^-tcl/o){
   $lang="tcl8";
   shift @ARGV;
}elsif($ARGV[0] =~ /^-py/o){
   $lang="python";
   shift @ARGV;
}


while(<>){
   if(/^\s*class\s+(\w+)/o){
      gen_class_typemap($1);
      print;
      $print_on=0;
      $need_right_curly=1;
      next;
   }elsif(/^\s*public:/o){
      $print_on=1;
      #next;
   }elsif(/^\s*private:/o){
      $print_on=0;
   }elsif(/^\s*protected:/o){
      $print_on=0;
   }elsif(/^\s*\}\s*;/o && $need_right_curly){
      $print_on=0;
      print;
      $need_right_curly=0;
      next;
   }
   if($print_on){
      if(/addNoShieldNet\(/o || /has(No)?Shield(Net)?/o){ print "//";}
      if(/\*\*\*/o){
      }else{
         s/int\s*\*\s*\w+/int* L_OUTPUT/go;
      }
      s/char\s*\*\*\s*\w+\s*([,\)])/char** L_OUTPUT$1/go;
      print;
   }
}
close(F);

sub gen_class_typemap{
   my ($cname)=@_;

if($lang eq "python"){
   print F << "END";
#if defined(SWIGPYTHON)
%typemap(out) $cname *{
    char cbuf[256];
    PyObject *func=PyObject_GetAttrString(py_mod,"${cname}Ptr");
    SWIG_MakePtr(cbuf,(void*)\$1,SWIGTYPE_p_$cname);
    \$result=PyEval_CallFunction(func, "(s)",cbuf);
    Py_DECREF(func);
}
#endif
END
}elsif($lang eq "tcl8"){
   print F << "END";
#if defined(SWIGTCL)
%typemap(out) $cname *{
    Tcl_Obj *newObj=SWIG_Ptr2Obj(interp,"$cname",SWIGTYPE_p_${cname},\$1);
    Tcl_SetObjResult(interp, newObj);
}
#endif
END
}
}
